﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Rope : MonoBehaviour
{
    [SerializeField] LineRenderer lineRenderer;
    [SerializeField] bool enableCollision = true;
    HingeJoint2D[] joint2Ds;
    Transform[] points;
    private Rigidbody2D root, end;
    
    // Start is called before the first frame update
    void Awake()
    {
        var list = GetComponentsInChildren<Rigidbody2D>().ToList();
        List<HingeJoint2D> jList = new List<HingeJoint2D>();
        foreach (var item in list)
        {
            if (item.name == "end")
            {
                end = item;
            }
            else if (item.name == "root")
            {
                root = item;
            }
            else {
                jList.Add(item.GetComponent<HingeJoint2D>());
            }
        }
        joint2Ds = jList.ToArray();


        float myY = transform.position.y;

        lineRenderer.positionCount = joint2Ds.Length + 2;
        points = new Transform[lineRenderer.positionCount];
        points[0] = root.transform;

        for (int i = 0; i < joint2Ds.Length; i++)
        {
            joint2Ds[i].transform.localPosition = new Vector3(0,- i, 0);
            if (i==0)
            {
                joint2Ds[i].connectedBody = root;
                
            }
            else
            {
                joint2Ds[i].connectedBody = joint2Ds[i - 1].GetComponent<Rigidbody2D>();
            }
            
            if (i+1==joint2Ds.Length)
            {
                end.transform.localPosition = new Vector3(0, - i - 1, 0);
                end.GetComponent<HingeJoint2D>().connectedBody= joint2Ds[i].GetComponent<Rigidbody2D>();
                
            }

            points[i + 1] = joint2Ds[i].transform;
        }
        
        points[points.Length - 1] = end.transform;

        foreach (var item in joint2Ds)
        {
            item.enableCollision = enableCollision;
            item.GetComponent<CapsuleCollider2D>().enabled = enableCollision;
        }
    }

    // Update is called once per frame
    void Update()
    {
        for (int i = 0; i < points.Length; i++)
        {
            lineRenderer.SetPosition(i, points[i].position);
        }
    }

    public void DropItem()
    {
        end.GetComponent<HingeJoint2D>().connectedBody = null;
    }
}
